<template>
  <layout-body>
    <div class="p20">
      <el-tree
        icon="ArrowRight"
        :data="ruleList"
        show-checkbox
        node-key="id"
        ref="treeRef"
        :check-strictly="true"
        default-expand-all	
        :props="{ children: 'children', label: 'label', class: 'rule-box' }"
      >
      </el-tree>
      <div class="flex center mt20">
        <back-btn text="取消"></back-btn>
        <el-button type="primary" @click="saveOk()" :loading="btnLoading" :disabled="btnLoading">确定</el-button>
      </div>
    </div>
  </layout-body>
</template>
<script lang="ts" setup>
import { onMounted, ref, getCurrentInstance } from "vue";
import { getRoleRule } from "@/api/system/role";
import { ElTree } from "element-plus";
import { useRouter } from "vue-router";
import { saveRules,getDetail } from "@/api/system/role";

const router = useRouter();
const {
  proxy: { $utils },
} = getCurrentInstance() as any;

const treeRef = ref<InstanceType<typeof ElTree>>();

const ruleList = ref();

const toInit = () => {
  getRoleRule()
    .then((res) => {
      ruleList.value = res.data;
    })
    .catch((error) => {});
    getDetail({id:roleId.value})
    .then(res => {
      treeRef.value!.setCheckedKeys(res.data.rules, false)
    })
    .catch(res => {
      $utils.errorMsg(res);
    });
};

const btnLoading = ref(false)

const saveOk = () => {
  if(btnLoading.value){
    return
  }
  btnLoading.value = true
  saveRules({
    id: roleId.value,
    rules: treeRef.value!.getCheckedKeys(false),
  })
    .then((res) => {
      $utils.successMsg(res.message);
      router.back()
    })
    .catch((error) => {
      $utils.errorMsg(error);
      btnLoading.value = false
    });
};

const roleId = ref("0");

onMounted(() => {
  let query = router.currentRoute.value.query;
  if (query && query.id) {
    roleId.value = String(query.id);
  }
  toInit();
});
</script>